{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## Pull Marquee Carbon Analytics Data with GS Quant\n",
    "\n",
    "### Permission Prerequisites\n",
    "\n",
    "To execute all the code in this tutorial, you will need the following application scopes:\n",
    "- **read_financial_data**\n",
    "\n",
    "## Authenticate and Initialize Your Session\n",
    "\n",
    "First you will import the necessary modules and add your client id and client secret."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "from IPython.display import display\n",
    "from gs_quant.api.gs.assets import GsAssetApi\n",
    "from gs_quant.api.gs.carbon import CarbonCoverageCategory, CarbonEmissionsIntensityType\n",
    "\n",
    "from gs_quant.markets.portfolio_manager import PortfolioManager\n",
    "from gs_quant.session import GsSession, Environment\n",
    "\n",
    "client = None\n",
    "secret = None\n",
    "scopes = None\n",
    "\n",
    "## External users must fill in their client ID and secret below and comment out the line below\n",
    "\n",
    "#client = 'ENTER CLIENT ID'\n",
    "#secret = 'ENTER CLIENT SECRET'\n",
    "#scopes = ('read_financial_data',)\n",
    "\n",
    "GsSession.use(\n",
    "    Environment.PROD,\n",
    "    client_id=client,\n",
    "    client_secret=secret,\n",
    "    scopes=scopes\n",
    ")\n",
    "\n",
    "print('GS Session initialized.')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Define Your Entity\n",
    "\n",
    "Carbon Analytics can be pulled from any object that inherits from the `PositionedEntity` class, such as `PortfolioManager`, `Index` or `Basket`. In this example, we will get analytics for a Marquee portfolio."
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "pm = PortfolioManager('ENTER PORTFOLIO ID')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Pull Carbon Analytics\n",
    "\n",
    "There are various parameters each of these methods take in.\n",
    " - reporting_year - takes 'Latest' and last 4 complete years i.e., from T-2 to T-5. defaults to Latest\n",
    " - currency - uses 'Currency' enum, defaults to the entity currency.\n",
    " - include_estimates - Parameter to choose if estimated emissions are to be included or not, defaults to false.\n",
    " - use_historical_data - Parameter to choose historical positions or backcast latest composition, defaults to false.\n",
    " - normalize_emissions - Parameter to normalize entity notional to 1,000,000 in denominated currency passed.\n",
    " - analytics_view - Parameter to view analytics using long component or short component of the portfolio\n",
    " - scope - uses 'CarbonScope' enum with totalGHG, scope1, scope2 values, defaults to totalGHG.\n",
    " - coverage_category - category for data coverage, uses 'CarbonCoverageCategory' enum with weights and numberOfCompanies, defaults to weights.\n",
    " - target_coverage_category - category for SBTI and Net Zero Targets, uses 'CarbonTargetCoverageCategory' enum with portfolioEmissions and capitalAllocated, defaults to portfolioEmissions.\n",
    " - classification - classification to group financed emissions, uses CarbonEmissionsAllocationCategory with sector, industry and region, defaults to sector\n",
    " - intensity_metric - intensity metric to query attribution for, uses CarbonEmissionsIntensityType with enterprise value, marketcap and revenue. defaults to enterprise value.\n",
    " - benchmark_id - Marquee identifier for the benchmark to do attribution analysis with."
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### Data Coverage\n",
    "\n",
    "Pull the data coverage for a reporting year based on weights or number of companies in the entity. You can choose to include estimated emissions, choose between using historical compositions or backcasting latest composition"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "print('Data Coverage:')\n",
    "display(pm.get_carbon_coverage(include_estimates=True, coverage_category=CarbonCoverageCategory.NUMBER_OF_COMPANIES))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### SBTI and Net Zero Emissions Target Coverage\n",
    "\n",
    "Pull Science Based Target Coverage and Net Zero Emissions Target Coverage for a reporting year based on capital allocated or portfolio emissions."
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "print('Science Based Target and Net Zero Emissions Target Coverage:')\n",
    "display(pm.get_carbon_sbti_netzero_coverage(include_estimates=True))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### Financed Emissions and Emissions Intensity profile\n",
    "\n",
    "Pull Financed Emissions profile and intensity metrics for a reporting year in respective denomination. Other parameters are to include estimates, use historical data, normalize emissions."
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "print('Financed Emissions and Intensity Profile:')\n",
    "display(pm.get_carbon_emissions(include_estimates=True))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### Financed Emissions by sector, industry and region\n",
    "\n",
    "Aggregate financed emissions and capital for each of the categories for a reporting year in respective denomination. We can pass a scope to look at specific scope."
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "print('Financed Emissions by Sector:')\n",
    "display(pm.get_carbon_emissions_allocation(include_estimates=True))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### Attribution analysis with benchmark\n",
    "\n",
    "Pull up brinson attribution analysis for sector allocation and security selection with respect to benchmark. Pass in the benchmark id, intensity type.\n",
    "\n",
    "Benchmark can be either an asset id or a portfolio id. For an asset, get the asset id by resolving the identifier and, for a portfolio use the portfolio id.\n",
    "\n",
    "Resolve asset id from identifier:"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "identifier = 'SPX'\n",
    "mqids = GsAssetApi.resolve_assets(identifier=[identifier], fields=['id'], limit=1)\n",
    "try:\n",
    "    benchmark_id = mqids[identifier][0]['id']\n",
    "except:\n",
    "    raise ValueError('Error in resolving the following identifier: ' + identifier)\n",
    "\n",
    "print('Attribution Analysis:')\n",
    "display(pm.get_carbon_attribution_table(benchmark_id=benchmark_id, include_estimates=True, intensity_metric=CarbonEmissionsIntensityType.EI_REVENUE))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "You can also pull up the whole analytics using 'get_carbon_analytics()'.\n",
    "\n",
    "*Other questions? Reach out to the [Portfolio Analytics team](mailto:gs-marquee-analytics-support@gs.com)!*"
   ],
   "metadata": {
    "collapsed": false
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}